package com.jxtpro.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jxtpro.config.util.StringKit;

import net.dreamlu.api.oauth.OauthQQ;
import net.dreamlu.api.util.TokenUtil;
/**
 * qq登录页控制器
 * @author x
 *
 */
public class QQController2 extends Controller{
	//OAuth2.0标准协议建议，利用state参数来防止CSRF攻击。可存储于session或其他cache中
	private static final String SESSION_STATE = "_SESSION_STATE_QQ_";

	/**
	 * 构造授权请求url
	 * @param     设定文件
	 * @return void    返回类型
	 * @throws
	 */
	public void index() {
	    try {
	        String state = TokenUtil.randomState();
	        setSessionAttr(SESSION_STATE, state);
	        redirect(OauthQQ.me().getAuthorizeUrl(state));
	    } catch (Exception e) {
	        redirect("/index.html");
	    }
	}
	
	/**
	 * 腾讯回调
	 * @Title: callback
	 * @param     设定文件
	 * @return void    返回类型
	 * @throws
	 * 返回json:<url>http://wiki.connect.qq.com/get_user_info</url>
	 */
	public void callback() {
	    String code = getPara("code");
	    String state = getPara("state");
	    String session_state = getSessionAttr(SESSION_STATE);
	    // 取消了授权
	    if (StringKit.isBlank(state) || StringKit.isBlank(session_state) || !state.equals(session_state) || StringKit.isBlank(code)) {
	        redirect("/admin.html");
	        return;
	    }
	    removeSessionAttr(SESSION_STATE);
	    try{
	        JSONObject userInfo = OauthQQ.me().getUserInfoByCode(code);
	        String type = "qq";
	        String openid = userInfo.getString("openid");
	        String nickname = userInfo.getString("nickname");
	        String photoUrl = userInfo.getString("figureurl_2");
	        // 将相关信息存储数据库...
	        System.out.println(type + ";"+openid+";"+nickname+";"+photoUrl);
	    }catch(Exception e){
	    }
	    redirect("/admin.html");
	}
}
